//
//  NewWorking.m
//  TableView&CollectionView
//
//  Created by 吴佳城 on 15/12/21.
//  Copyright © 2015年 李东旭. All rights reserved.
//

#import "NewWorking.h"
#import <AFNetworking.h>
#import <CommonCrypto/CommonCrypto.h>
#import "Reachability.h"

@implementation NewWorking

+(void)GetDayaWithURL:(NSString *)urlStr dic:(NSDictionary *)dic sussess:(void (^)(id))response filed:(void (^)(NSError *))err
{
    //只支持xcode7.0以上版本 + AFNetWorking3.0以上版本使用
    //如果是Xcode7.0一下版本 + AFNetWorking2.x版本,继续使用AFHttpRequestOperationManager
    
#warning 2.判断网络状态
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    //判断网络状态(不等于0代表有网)
    if ( 0 != reach.currentReachabilityStatus) {
    
    AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
    
    //有的返回的数据类型,AFN不支持解析,我们需要设置一下,让AFN支持解析
    [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    [man GET:urlStr parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //返回数据给调用方 response(是一个block) responseObject(返回的数据类型id类型)
        response(responseObject);
        
        //调用获取缓存路径方法,把网址和网络请求成功的值传进去
        [self cachePath:urlStr response:responseObject type:0];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        err(error);
    }];
    }
    //无网走缓存
    else{
        
        //response 后面参数, 因为我们没走网络请求,我不是需要缓存数据,而是要获取数据
        
        id data = [self cachePath:urlStr response:nil type:1];
        
        //如果找到那个文件夹,则取 (写个保护)
        if (data != nil) {
            
            response(data);
        }
    }
}

+(id)cachePath:(NSString *)urlStr response:(id)responseObject type:(NSInteger)type
{
#warning 1.开始缓存
    //1.把我们的网址利用MD5加密算法转换成数字和字符串的组合(因为网址不能直接作为文件名)
    
    //如果self 后面调用的是-号方法,那么这个self就是本类的对象.例如:Person *per = nil, self就是这个per
    //如果self 后面调用的是+号方法.那么这个self就是本类的名字(因为网址不能直接作为文件名)
    NSString *fileName = [self cachedFileNameForKey:urlStr];
    
    //2.找到cache文件夹在沙盒中的路径
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    
    //3.路径文件名拼接
    NSString *cacheP = [cachePath stringByAppendingPathComponent:fileName];
    
    //4.把网络请求成功的数据(归档)
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:responseObject];
    
    //如果type是0,代表我要写入 1 读取
    if (0 == type) {
    //5.写入本地
    [data writeToFile:cacheP atomically:YES];
    }
    else if (1 == type)
    {
        //读取
        id data = [NSKeyedUnarchiver unarchiveObjectWithFile:cacheP];
        
        return data;
    }
    
    NSLog(@"%@",cacheP);
    
    return nil;
}

+(void)PostDayaWithURL:(NSString *)urlStr dic:(NSDictionary *)dic sussess:(void (^)(id))response filed:(void (^)(NSError *))err
{
#warning 判断网络状态
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    if (0 != reach.currentReachabilityStatus) {
        
        AFHTTPSessionManager *man = [AFHTTPSessionManager manager];
        
        [man.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
        
        [man POST:urlStr parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //返回数据给调用方 response(是一个block) responseObject(返回的数据类型id类型)
            response(responseObject);
            
            //调用获取缓存路径方法,把网址和网络请求成功的值传进去
            [self cachePath:urlStr dic:dic response:responseObject type:0];
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            err(error);
        }];
        
    }
    //无网走缓存
    else{
        
        //response 后面参数, 因为我们没走网络请求,我不是需要缓存数据,而是要获取数据
        
        id data = [self cachePath:urlStr dic:dic response:nil type:1];
        
        //如果找到那个文件夹,则取 (写个保护)
        if (data != nil) {
            
            response(data);
        }
    }
}

+(id)cachePath:(NSString *)urlStr dic:(NSDictionary *)dic response:(id)responseObject type:(NSInteger)type
{
    //1.把网址+parameters利用MD5加密算法转化成数字+字符串组合
    NSString *url = [NSString stringWithFormat:@"%@%@",urlStr, [dic allValues]];
    
    NSString *fileName = [self cachedFileNameForKey:url];
    
    //2.找到cache文件夹在沙盒中的路径
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    
    //3.路径文件名拼接
    NSString *cacheP = [cachePath stringByAppendingPathComponent:fileName];
    
    //4.把网络请求成功的数据归档
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:responseObject];
    
    //如果type是0,代表我要写入
    //如果type是0,代表我要写入 1 读取
    if (0 == type) {
        //5.写入本地
        [data writeToFile:cacheP atomically:YES];
    }
    else if (1 == type)
    {
        //读取
        id data = [NSKeyedUnarchiver unarchiveObjectWithFile:cacheP];
        
        return data;
    }
    
    return nil;
    
}
// 利用MD5算法把网址转换成一串数字加字母
+ (NSString *)cachedFileNameForKey:(NSString *)key {
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    return filename;
}

@end
